package edu.hhu.dynamic.table;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: SQ
 * Date: 15-8-7
 * Time: 下午7:21
 * To change this template use File | Settings | File Templates.
 */
public class Excel {
    public void writeExcel(String filename)throws IOException {
        //创建新的Excel工作薄
        HSSFWorkbook workbook=new HSSFWorkbook();
        //在Excel中新建一张工作表，起名为jsp
        HSSFSheet sheet=workbook.createSheet("Jsp");
        //创建第一行
        HSSFRow row=sheet.createRow(0);
        //创建第一列
        HSSFCell cell=row.createCell(0);
        //定义单元格为字符串类型
        cell.setCellType(HSSFCell.CELL_TYPE_STRING);
        //在单元格输入一些     内容
        cell.setCellValue(new Date());
        //        新建输出流
        FileOutputStream fout=new FileOutputStream(filename);
        //存盘
        workbook.write(fout);

        fout.flush();
        //结束关闭
        fout.close();
    }

    public void readExcel(String filename)throws FileNotFoundException,IOException{
        HSSFWorkbook workbook=new HSSFWorkbook(new FileInputStream(filename));
        //按名字引用Excel工作表
        HSSFSheet sheet=workbook.getSheet("Jsp");
        //按索引获取工作表
        //HSSFSheet sheet=workbook.getSheetAt(0);
        HSSFRow row=sheet.getRow(0);
        HSSFCell cell=row.getCell(0);
        //打印读取的值
        System.out.print(cell.getStringCellValue());
        cell=row.getCell(1);
        System.out.println(cell.getStringCellValue());
    }

    public static void main(String[] args){
        Excel excel=new Excel();
        try{
            excel.writeExcel("D:\\test.xls");
            excel.readExcel("D:\\test.xls");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
